<template>
 <!-- 自定义对话框 -->
 <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="basicOrderCRUD"
      header="*订单"
      width="800px"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-row :gutter="[20, 20]" style="width: 100%">
        <t-col :span="6">
          <t-form-item label="订单类型" name="decorationType" :rules="[{ required: true, message: '请选择订单类型' }]">
            <t-select
              v-model:value="formData.decorationType"
              :options="dictionaryStore.get('decoration_order_type')"
              placeholder="请选择订单类型"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.decorationType = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户名称" name="name" :rules="[{ required: true, message: '请输入客户名称' }]">
            <t-input v-model:value="formData.name" placeholder="请输入客户名称" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户性别" name="sex" :rules="[{ required: true, message: '请选择客户性别' }]">
            <t-select
              v-model:value="formData.sex"
              :options="dictionaryStore.get('system_user_sex')"
              placeholder="请选择客户性别"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.sex = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户等级" name="customerLevel">
            <t-select
              v-model:value="formData.customerLevel"
              :options="dictionaryStore.get('decoration_order_customer_level')"
              placeholder="请选择客户等级"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.customerLevel = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6"  v-if="formData.customerLevel === '4'">
          <t-form-item
            v-if="formData.customerLevel === '4'"
            label="交房时间"
            name="handoverTime"
            :rules="[{ required: true, message: '请选择交房时间' }]"
          >
            <t-date-picker
              allow-input
              v-model:value="formData.handoverTime"
              clearable
              default-time="23:59:59"
              enable-time-picker
              placeholder="请选择交房时间"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item
            label="手机号码"
            name="phone"
            :rules="[
              { required: !formData.wxCode, message: '请输入手机号码' },
              { telnumber: true, message: '请输入正确的手机号码' },
            ]"
          >
            <t-input
              v-model:value="formData.phone"
              placeholder="请输入手机号码"
              clearable
              :readonly="readonly"
              maxlength="11"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item
            label="微信号码"
            name="wxCode"
            :rules="[{ required: !formData.phone, message: '请输入微信号码' }]"
          >
            <t-input v-model:value="formData.wxCode" placeholder="请输入微信号码" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="归属城市" name="adCode" :rules="[{ required: true, message: '请选择归属城市' }]">
            <t-cascader
              v-model:value="formData.adCode"
              :options="city.tree"
              :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
              placeholder="请选择归属城市"
              filterable
              clearable
              :readonly="readonly"
              value-type="full"
              @change="(value: any) => handleAdCodeChange(value, formData)"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="来源渠道" name="channelSource" :rules="[{ required: true, message: '请选择来源渠道' }]">
            <t-select
              v-model:value="formData.channelSource"
              :options="channelList"
              :keys="{ value: 'id', label: 'name' }"
              placeholder="请选择来源渠道"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.channelSource = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="楼盘名称" name="propertyName" :rules="[{ required: true, message: '请选择楼盘名称' }]">
            <t-select
              v-model:value="formData.propertyName"
              v-model:popup-visible="formData.popupVisible"
              placeholder="请选择楼盘名称"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.propertyName = null"
            >
              <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
                {{ _.name }}
                <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
              </t-option>
              <template #panelBottomContent>
                <!-- 快捷添加楼盘信息 -->
                <quick-add-property-info
                  @open="formData.popupVisible = false"
                  @close="getPropertyClose"
                />
              </template>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="详细地址" name="address">
            <t-input v-model:value="formData.address" placeholder="请输入详细地址" clearable :readonly="readonly" />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="房屋户型" name="houseType" :rules="[{ required: true, message: '请选择房屋户型' }]">
            <t-select
              v-model:value="formData.houseType"
              :options="dictionaryStore.get('decoration_order_house_type')"
              placeholder="请选择房屋户型"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.houseType = null"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="房屋面积(㎡)" name="houseArea" :rules="[{ required: true, message: '请输入房屋面积' }]">
            <t-input-number
              v-model:value="formData.houseArea"
              placeholder="请输入房屋面积"
              :min="0"
              :allow-input-over-limit="false"
              clearable
              :readonly="readonly"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="归属公司" name="companyId" :rules="[{ required: true, message: '请选择归属公司' }]">
            <t-select
              v-model:value="formData.companyId"
              :options="companyList"
              :keys="{ value: 'id', label: 'name' }"
              placeholder="请选择归属公司"
              clearable
              filterable
              :readonly="readonly"
              @clear="formData.companyId = null"
            />
          </t-form-item>
        </t-col>
        <t-col v-if="mode === 'create'" :span="6">
          <t-form-item label="回访内容" name="lastMessage" :rules="[{ required: true, message: '请输入回访内容' }]">
            <t-textarea v-model:value="formData.lastMessage" placeholder="请输入回访内容" :readonly="readonly" />
          </t-form-item>
        </t-col>
      </t-row>
    </custom-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef } from 'vue';

import { basicOrderCRUD } from '@/api/order/basic';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import city from '@/utils/city';
import CustomDialog from '@/components/custom/dialog/index.vue';
import QuickAddPropertyInfo from '@/pages/config/property/components/QuickAddPropertyInfo.vue';
import { useDictionaryStore } from '@/store';
import { propertyManageCRUD } from '@/api/config/property';
import { channelManageCRUD } from '@/api/config/common-config';


// 公司列表
const companyList = ref([]);
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// emits
const emits = defineEmits(['requestSuccess']);
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.province = value[0] || '';
  params.city = value[1] || '';
  params.area = value[2] || '';
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.adCode = [];
  if (params.province) params.adCode.push(params.province);
  if (params.city) params.adCode.push(params.city);
  if (params.area) params.adCode.push(params.area);
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 渠道列表
const channelList = ref([]);
// 处理获取渠道列表
const handleGetChannelList = () => {
  const params = {
    pageSize: -1,
  };
  channelManageCRUD
    .page(params)
    .then((data) => {
      channelList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetChannelList();
const getPropertyClose = () => {
  customDialogRef.value.formData.popupVisible = true
  
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
      customDialogRef.value.formData.propertyName=propertyInfoList.value[0].id
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });

}
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetPropertyInfoList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};

defineExpose({
  handleOpenDialog,
});
</script>
